<template>
  <div class="container">
    <Breadcrumb :items="['menu.menuManage', 'menu.adminMenu']" />
    <a-card class="custom-card" title="">
      <a-row style="margin-bottom: 16px">
        <a-col :span="16">
          <a-space>
            <a-button v-if="isExpandAll" type="primary" status="warning" @click="expandAll(isExpandAll)">
              <template #icon><icon-caret-down /></template>展开
            </a-button>
            <a-button v-else type="dashed" status="warning" @click="expandAll(isExpandAll)">
              <template #icon><icon-caret-up /></template>收缩
            </a-button>
            <a-button v-if="checkPermission(['adminmenu/add'])" type="primary" @click="add({}, 'add')">
              <template #icon><icon-plus /></template>
              <template #default>添加</template>
            </a-button>
          </a-space>
        </a-col>
        <a-col :span="8" style="text-align: right">

        </a-col>
      </a-row>
      <a-table
        ref="tableRef"
        row-key="id"
        :loading="loading"
        :pagination="false"
        :data="renderData"
        size="medium"
        :bordered="{ wrapper: true, cell: true }"
        :row-selection="rowSelection"
        :scroll="tableScroll"
        column-resizable
        @selection-change="selectionChange"
      >
        <template #columns>
          <a-table-column title="名称" data-index="name" :width="200"/>
          <a-table-column title="应用" data-index="app" :width="100"/>
          <a-table-column title="控制器" data-index="controller" :width="180"/>
          <a-table-column title="方法" data-index="action" :width="100"/>
          <a-table-column title="路由" data-index="route" :width="180"/>
          <a-table-column title="图标" data-index="icon" align="center" :width="80">
            <template #cell="{ record }">
<!--              <span v-if="record.icon">{{ `<${record.icon} />` }}</span>-->
              <span v-if="record.icon" v-html="`<${record.icon} />`"></span>
            </template>
          </a-table-column>
          <a-table-column title="" data-index="status" align="center" :width="120">
            <template #title>
              <span>是否禁用</span>
              <a-tooltip content="禁用后无法访问">
                <icon-question-circle-fill />
              </a-tooltip>
            </template>
            <template #cell="{ record }">
              <a-switch v-model="record.status" :checked-value="1" :unchecked-value="2" @change="isActivate(record)"/>
            </template>
          </a-table-column>
          <a-table-column title="排序" data-index="sorting" align="center" :width="100">
            <template #cell="{ record }">
              <a-input-number v-model="record.sorting" :step="1" @blur="listOrders(record)" />
            </template>
          </a-table-column>
          <a-table-column title="创建时间" data-index="created_at" align="center" :width="180"/>
          <a-table-column title="操作" data-index="operations" align="center" fixed="right" :width="95">
            <template #cell="{ record }">
<!--              <a-space>
                <a-tooltip content="添加子菜单">
                  <a-button type="primary" size="small" @click="add(record, 'add')"><icon-plus /></a-button>
                </a-tooltip>
                <a-button type="primary" size="small" @click="add(record, 'edit')"><icon-edit /></a-button>
                <a-button type="primary" status="danger" size="small" @click="del([record])"><icon-delete /></a-button>
                <a-button type="primary" status="warning" size="small" @click="copy(record)">复制</a-button>
              </a-space>-->
              <a-dropdown>
                <a-button type="text" size="mini">操作 <icon-down /></a-button>
                <template #content>
                  <a-doption @click="add(record, 'add')">添加子菜单</a-doption>
                  <a-doption @click="add(record, 'edit')">编辑</a-doption>
                  <a-doption class="is-danger" @click="del([record])">删除</a-doption>
                  <a-doption @click="copy(record)">复制</a-doption>
                </template>
              </a-dropdown>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <Detail ref="detailRef" :treeDatas="treeDatas" @saveCallback="fetchData"/>

    <a-modal
      v-model:visible="copyDialogVisible"
      :title="copyDialogTitle"
      :mask-closable="false"
      @before-ok="copyDialogBeforeOk"
    >
      <a-form ref="copyFormRef" :model="copyData">
        <a-form-item field="parent_id" label="上一级" label-col-flex="120px">
          <a-cascader
            v-model="copyData.parent_id"
            :options="treeDatas"
            :field-names="{ value: 'id', label: 'name' }"
            placeholder="一级菜单"
            check-strictly
            allow-search
            allow-clear
          />
        </a-form-item>
        <a-form-item field="is_child" label="是否复制子集" label-col-flex="120px">
          <a-radio-group v-model="copyData.is_child">
            <a-radio :value="1">是</a-radio>
            <a-radio :value="0">否</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, h, compile, getCurrentInstance } from 'vue';
  import { useI18n } from 'vue-i18n';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { Message, Modal } from '@arco-design/web-vue';

  import useLoading from '@/hooks/loading';
  import screenHeight from '@/utils/screen-height';
  import checkPermission from '@/utils/permission';
  import { DataState, apiList, apiDel, apiDisable, apiListOrders, apiCopy } from '@/api/menu';
  import Detail from './components/detail.vue';

  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const height = screenHeight(265);
  // const { proxy } = <any>getCurrentInstance();
  const { proxy } = getCurrentInstance() as any;
  const renderData = ref<DataState[]>([]);
  const treeDatas = ref<DataState[]>([]);
  const rowSelection = reactive({
    type: 'checkbox' as const,
    showCheckedAll: true,
  });
  const tableScroll = ref({
    x: '100%',
    y: height,
  });

  let selectionKeys: string[] = []; // 选中项ID
  const isExpandAll = ref(true); // 展开/收缩
  const detailRef = ref();

  const copyFormRef = ref<FormInstance>();
  const copyData = ref({
    id: '',
    parent_id: '',
    is_child: 1,
  });
  const copyDialogVisible = ref(false);
  const copyDialogTitle = ref();

  // 列表
  const fetchData = async () => {
    setLoading(true);
    try {
      const { data } = await apiList();
      renderData.value = data.data;
      treeDatas.value = data.data;
      // object（对象）array（数组）这两个类型进行等于赋值的时候实际上是进行的引用，源数据改变后目标数据也就发生了变换
      // treeDatas.value = renderData.value // 原始的的数据是一个数组或者对象，对于一个对象或者数组的时候他们等于是引用的地址是相同的，所以treeDatas改变时datas也会跟着改变
      // treeDatas.value = JSON.parse(JSON.stringify(renderData.value))
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  // 添加/编辑
  const add = (row?: any, type?: string) => {
    detailRef.value.fetchData(row, type);
  };
  // 删除
  const del = (row: any[]) => {
    if (!row.length) {
      selectMsg();
    } else {
      let title = '删除';
      let message = `确定要删除选中的 <span style="color:red">${row.length} </span> 条数据吗？`;
      let ids = row;
      if (row.length === 1 && row[0].id) {
        title = `${title}ID：${row[0].id}`;
        message = `确定要删除 <span style="color:red">${row[0].name} </span> 这条数据吗？`;
        ids = [row[0].id];
      }
      Modal.warning({
        title,
        content: () => h(compile(message)),
        closable: true,
        hideCancel: false,
        onOk: async () => {
          setLoading(true);
          try {
            await apiDel({ids});
          } catch (err) {
            setLoading(false);
          } finally {
            fetchData();
            setLoading(false);
          }
        },
      });
    }
  };
  // 启用/禁用
  const isActivate = async (row: DataState) => {
    setLoading(true);
    await apiDisable({
      id: row.id,
      status: row.status,
    });
    fetchData();
  };
  // 更新排序
  const listOrders = async (row: DataState) => {
    await apiListOrders({
      ids: row.id,
      sorting: row.sorting,
    }).then(res => {
      Message.success('更新排序成功');
    });
  };
  // 复制
  const copy = async (row: any) => {
    copyData.value.id = row.id;
    copyDialogVisible.value = true;
    copyDialogTitle.value = '复制';
  };
  const copySubmit = async (done: any) => {
    try {
      const ruleRes = await copyFormRef.value?.validate();
      if (!ruleRes) {
        await apiCopy(copyData.value);
        done();
        fetchData();
      } else {
        done(false);
      }
    } catch (err) {
      done(false);
    } finally {
      done(false);
    }
  };

  // 已选择的数据行发生改变时触发 -- table 表头
  const selectionChange = (rowKeys: any[]) => {
    selectionKeys = rowKeys;
  };
  const selectMsg = (message?: string) => {
    Message.info(message || '请选择需要操作的数据');
  };
  // 批量删除
  const batchDel = () => {
    del(selectionKeys);
  };

  // 展开/收起
  const expandAll = (isExpand: boolean) => {
    isExpandAll.value = !isExpand;
    // expandFor(renderData.value, isExpand);
    proxy.$refs.tableRef.expandAll(isExpand);
  };
  // const expandFor = (data, isExpand: boolean) => {
  //   data.forEach(i => {
  //     proxy.$refs.tableRef.expand(i, isExpand);
  //     if (i.children) {
  //       expandFor(i.children, isExpand);
  //     }
  //   });
  // };

  const copyDialogBeforeOk = (done: any) => {
    copySubmit(done);
  };

  fetchData();
</script>

<script lang="ts">
  export default {
    name: 'AdminMenu',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
</style>
